package com.kzw.oa.system.web;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kzw.core.bean.Msg;
import com.kzw.core.util.StringUtil;
import com.kzw.misc.utils.AppUtil;
import com.kzw.oa.system.model.AppUser;
import com.kzw.oa.system.model.SysConfig;
import com.kzw.oa.system.model.SystemLog;
import com.kzw.oa.system.service.AppUserService;
import com.kzw.oa.system.service.SysConfigService;
import com.kzw.oa.system.service.SystemLogService;

import nl.captcha.Captcha;

@Controller
public class LoginAction {

	// must be same to app-security.xml
	private String key = "RememberAppUser";

	// private String rememberMe;//自动登录
	@Autowired
	private AppUserService appUserService;
	@Autowired
	private SysConfigService sysConfigService;
	@Autowired
	private AuthenticationManager authenticationManager;
	@Autowired
	private SystemLogService logService;

	/**
	 * jsp登录
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Msg login(String username, String password, String checkCode, 
			HttpServletRequest request, HttpServletResponse response) {

		AppUser user = appUserService.findUniqueBy("username", username);
		if (user == null) {
			Msg msg = new Msg(false, 1, "该用户账号不存在!");
			return msg;
		}
		if (user.getStatus() != 1) {
			Msg msg = new Msg(false, 1, "账号已经被禁用!");
			return msg;
		}
		// 取得验证码配置
		SysConfig codeConfig = sysConfigService.findUniqueBy("configKey", "codeConfig");

		// 判断密码及用户名是否一致
		String newPassword = StringUtil.encryptSha256(password);
		// 密码是否一致
		if (!user.getPassword().equals(newPassword)) {
			Msg msg = new Msg(false, 1, "密码不正确!");
			return msg;
		}

		// 检查验证码
		Captcha captcha = (Captcha) request.getSession().getAttribute(Captcha.NAME);
		// 判断是否需要验证码验证
		if (codeConfig != null && codeConfig.getDataValue().equals(SysConfig.CODE_OPEN)) {
			// 验证码验证
			if (captcha != null && !captcha.isCorrect(checkCode)) {
				Msg msg = new Msg(false, 1, "验证码不正确!");
				return msg;
			}
		}

		// 验证ip段，并记录谁使用非法IP登陆
		try {
			String ipValid = (String) AppUtil.getSysConfig().get("ipValid");
			if (ipValid != null && Boolean.parseBoolean(ipValid)) {
				String ipPattern = (String)AppUtil.getSysConfig().get("ipPattern");
				if (ipPattern != null) {
					String ip = request.getRemoteAddr();
					if (!ip.matches(ipPattern)) {
						SystemLog log = new SystemLog();
						log.setUserId(user.getUserId());
						log.setUsername(user.getUsername());
						log.setExeOperation("IP非法, " + ip);
						log.setCreatetime(new Date());
						logService.saveOrUpdate(log);
						Msg msg = new Msg(false, 1, "IP段非法，此用户被记录!");
						return msg;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
					username, StringUtil.encryptSha256(password));
			SecurityContext securityContext = SecurityContextHolder.getContext();
			securityContext.setAuthentication(authenticationManager.authenticate(authRequest));
			SecurityContextHolder.setContext(securityContext);
			request.getSession().setAttribute(
					UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
							username);

			
			String rememberMe = request.getParameter("_spring_security_remember_me");
			if (rememberMe != null && rememberMe.equals("on")) { // 加入cookie
				long tokenValiditySeconds = 1209600; // 14 days long
				long tokenExpiryTime = System.currentTimeMillis() + (tokenValiditySeconds * 1000);
				String signatureValue = DigestUtils.md5Hex(username + ":"
						+ tokenExpiryTime + ":" + user.getPassword() + ":"
						+ key);
				String tokenValue = username + ":" + tokenExpiryTime + ":" + signatureValue;
				String tokenValueBase64 = new String(Base64.encodeBase64(tokenValue.getBytes()));
				response.addCookie(makeValidCookie(request, tokenExpiryTime, tokenValueBase64));
			}
			 

			// 记录登陆日志信息
			SystemLog log = new SystemLog();
			log.setUserId(user.getUserId());
			log.setUsername(user.getUsername());
			log.setBoard("应用系统");
			log.setExeOperation("登陆系统");
			log.setCreatetime(new Date());
			logService.saveOrUpdate(log);

		} catch (Exception ex) {
			ex.printStackTrace();
			Msg msg = new Msg(false, 1, ex.getCause().getMessage());
			return msg;
		}
		return new Msg(true);
	}

	// add Cookie
	protected Cookie makeValidCookie(HttpServletRequest request, long expiryTime, String tokenValueBase64) {
		Cookie cookie = new Cookie(
				TokenBasedRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
				tokenValueBase64);
		cookie.setMaxAge(60 * 60 * 24 * 365 * 5); // 5 years
		cookie.setPath(org.springframework.util.StringUtils.hasLength(request
				.getContextPath()) ? request.getContextPath() : "/");
		return cookie;
	}



	/**
	 * 验证码 <未使用>
	 */
	public Msg validateCaptcha(HttpServletRequest request, String checkCode) {
		// 定义验证信息
		Msg msg = new Msg();
		// 取得验证码配置
		SysConfig codeConfig = sysConfigService.findUniqueBy("configKey", "codeConfig");

		// 取得验证码
		Captcha captcha = (Captcha) request.getSession().getAttribute(Captcha.NAME);

		// 判断是否需要验证码验证
		if (codeConfig != null && codeConfig.getDataValue().equals(SysConfig.CODE_OPEN)) {
			if (captcha == null) {
				msg.setMsg("请刷新验证码再登录！");
				msg.setSuccess(false);
			} else {
				// 验证码验证
				if (captcha.isCorrect(checkCode)) {
					msg.setSuccess(true);
				} else {
					msg.setMsg("验证码不正确！");
					msg.setSuccess(false);
				}
			}
		}
		return msg;
	}

}
